#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   Bootloader_RequestDownload_0x34_test.py
@Time    :   2022/10/13 10:35:23
@Author  :   Yang Liang
@Version :   1.0
@Contact :   yangliang@chengtech.com
@License :   (C)Copyright 2022-2025
@Desc    :   None
'''

# here put the import lib
import zipfile
from numpy import byte, bytes_, int16
from pytest_assume.plugin import assume
 
import pytest
import time
import requests
from sympy import I
# from sympy import assuming
from commDriver.TS_CAN import *
import allure
import sys
from collections.abc import Iterable
import Set_up

from sqlalchemy import false
sys.dont_write_bytecode = True

SID_0x34_RequestDownload_NRC = [([0x34],[0x7F,0x34,0x13],[0x34]),            
                              ([0x34,0x00],[0x7F,0x34,0x13],[0x34,0x00]),
                              ([0x34,0x00,0x44],[0x7F,0x34,0x13],[0x34,0x00,0x44]),
                              ([0x34,0x00,0x44,0x00,0x05,0x00,0x00,0x00,0x00,0x00],[0x7F,0x34,0x13],[0x34,0x00,0x44,0x00,0x05,0x00,0x00,0x00,0x00,0x00]),
                              ([0x34,0x00,0x33,0x05,0x00,0x00,0x00,0x00,0x00,0x00],[0x7F,0x34,0x13],[0x34,0x00,0x33,0x05,0x00,0x00,0x00,0x00,0x00,0x00]),
                              ([0x34,0x00,0x33,0x05,0x00,0x00,0x00,0x00,0x01],[0x7F,0x34,0x13],[0x34,0x00,0x33,0x05,0x00,0x00,0x00,0x00,0x01]),
                              ([0x34,0x01,0x44,0x00,0x05,0x00,0x00,0x00,0x00,0x00,0x01,0x01],[0x7F,0x34,0x13],[0x34,0x01,0x44,0x00,0x05,0x00,0x00,0x00,0x00,0x00,0x01,0x01]),
                              ([0x34,0x00,0x44,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01],[0x7F,0x34,0x13],[0x34,0x10,0x44,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01]),
                              ([0x34,0x10,0x44,0x00,0x03,0x00,0x00,0x00,0x00,0x00],[0x7F,0x34,0x13],[0x34,0x10,0x44,0x00,0x03,0x00,0x00,0x00,0x00,0x00])]  

SID_0x34_RequestDownload_NRC31 = [ ('34 00 44 00 05 00 00 FF FF FF FF','7F 34 31'), # APP地址正确，长度错误
                                   ('34 00 44 00 7A 00 00 FF FF FF FF','7F 34 31'), # flashdrv地址正确，长度错误
                                   ('34 00 44 00 02 00 00 FF FF FF FF','7F 34 31'), # pro_boot地址正确，长度错误
                                   ('34 00 44 00 02 A0 00 FF FF FF FF','7F 34 31'), # plus_boot地址 正确，长度错误 
                                   ('34 00 44 FF FF FF FF 00 09 7F 22','7F 34 31'), # 地址错误
                                   ('34 00 44 FF FF FF FF FF FF FF FF','7F 34 31'), # 地址长度都错误
                                   ('34 00 55 00 05 00 00 00 09 7F 22','7F 34 31'), # 
                                   ('34 11 44 00 05 00 00 00 09 7F 22','7F 34 31'),
                                   ('34 10 44 00 05 00 00 00 09 7F 22','7F 34 31'),
                                   ('34 01 44 00 05 00 00 00 09 7F 22','7F 34 31'),         
                                 ]  
                              
class Test_RequestDownload_Phy(object):

     ids = ["Request {2}".format(req,resp,binascii.b2a_hex(bytearray(send),' ')) for req,resp,send in SID_0x34_RequestDownload_NRC]
     @allure.severity('minor')
     @allure.description('Test NRC of 0x31 in bootloader with physical addressing')
     @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     @pytest.mark.parametrize('req,resp,title',SID_0x34_RequestDownload_NRC,ids = ids)
     def test_RequestDownload_NRC_Phy(self,action,Driver,req,resp,title):
          iStep = 1
          time.sleep(1)
          iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, req, resp, 2, iStep, True)

     @allure.severity('minor')
     @allure.description('Test NRC33 of 0x34 in programming session in bootloader with physical addressing')
     @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     def test_RequestDownload_NRC33_Phy(self,Driver,action):
          iStep = 1
          iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, [0x34,0x00,0x44,0x00,0x7A,0x00,0x00,0x00,0x00,0x28,0x0A], [0x7F,0x34,0x33], 2, iStep, False)

     # @allure.severity('minor')
     # @allure.description('Test NRC70 of 0x34 in programming session in bootloader with physical addressing')
     # @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     # def test_RequestDownload_NRC70_Phy(self,Driver,action):
     #      iStep = 1
     #      iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, [0x34,0x00,0x44,0x01,0x7A,0x00,0x00,0x00,0x00,0x28,0x0A], [0x7F,0x34,0x70], 2, iStep, True)

     # @allure.severity('minor')
     # @allure.description('Test NRC12 of 0x34 in programming session in bootloader with physical addressing')
     # @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     # def test_RequestDownload_NRC12_Phy(self,Driver,action):
     #      iStep = 1
     #      iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, [0x34,0x81,0x44,0x01,0x7A,0x00,0x00,0x00,0x00,0x28,0x0A], [0x7F,0x34,0x12], 2, iStep, True)


     @allure.severity('minor')
     @allure.description('Test NRC7F of 0x34 in programming session in bootloader with physical addressing')
     @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     def test_RequestDownload_NRC7F_Phy(self,Driver,action):
          iStep = 1
          iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, [0x34,0x00,0x44,0x00,0x7A,0x00,0x00,0x00,0x00,0x28,0x0A], [0x7F,0x34,0x7F], 3, iStep, True)

     ids = ["Request {0}".format(req,resp) for req,resp in SID_0x34_RequestDownload_NRC31]
     @allure.severity('minor')
     @allure.description('Test NRC31 of 0x31 in bootloader with physical addressing')
     @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     @pytest.mark.parametrize('req,resp',SID_0x34_RequestDownload_NRC31,ids = ids)
     def test_RequestDownload_NRC31_Phy(self,action,Driver,req,resp):
          iStep = 1
          time.sleep(1)
          iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, req, resp, 2, iStep, True)

     # @allure.severity('minor')
     # @allure.description('Test NRC31 of 0x34 in programming session in bootloader with physical addressing')
     # @allure.testcase('Test cases address:https://chengtech.pingcode.com/testhub/libraries/62a69d6cb35db4f20e37703a/cases')
     # def test_RequestDownload_NRC31_Phy(self,Driver,action):
     #      iStep = 1
     #      start_address,segment_size = self.GetAppAdressAndLength()
     #      #长度不对
     #      Request_download_CMD = [0x34,00,0x44] + \
     #                               [(start_address>>24) & 0xFF] + [(start_address>>16) & 0xFF] + [(start_address>>8) & 0xFF] + [(start_address) & 0xFF] +\
     #                               [0xFF] + [0xFF] + [0xFF] + [0xFF]
     #      iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, Request_download_CMD, [0x7F,0x34,0x31], 2, iStep, True)

     #      #地址不对
     #      Request_download_CMD = [0x34,00,0x44] + \
     #                               [0xFF] + [0xFF] + [0xFF] + [0xFF] +\
     #                               [(segment_size>>24) & 0xFF] + [(segment_size>>16) & 0xFF] + [(segment_size>>8) & 0xFF] + [(segment_size) & 0xFF]
     #      iStep,uds_resp, size = Driver['CAN'].checkReqResp(Driver, Request_download_CMD, [0x7F,0x34,0x31], 0, iStep)

     def GetAppAdressAndLength(self, path=Set_up.zipfile_path):
          app_filepath,flash_filepath,xml_filepath,boot_filepath = self.get_path(path)
          self.parse_file(app_filepath)
          for index,segment in enumerate(self.binfile_handle.segments):
               if(self.file_type == '.bin' or self.file_type == '.BIN'):
                    start_address = self.startaddress
                    segment_size = self.size
               else:
                    start_address = segment.minimum_address
                    segment_size = segment.maximum_address - segment.minimum_address

          return start_address, segment_size

     def get_path(self,zipPath):
          root = os.path.abspath(os.path.dirname(__file__))
          dirpath = os.path.join(root,r'temp')
          zFile = zipfile.ZipFile(zipPath, "r")
          self.app_filepath = ''
          self.app_filename = ''
          self.flash_filepath = ''
          self.flash_filename = ''
          self.xml_filepath = ''
          self.xml_filename = ''
          self.boot_name = ''
          self.boot_filepath = ''
          for fileM in zFile.namelist(): 
               zFile.extract(fileM, dirpath)
               if 'app' in fileM.lower():
                    self.app_filename=fileM
                    self.app_filepath = os.path.join(dirpath,fileM)
               elif 'flash' in fileM.lower():
                    self.flash_filename=fileM
                    self.flash_filepath = os.path.join(dirpath,fileM)
               elif 'xml' in fileM.lower():
                    self.xml_filename=fileM
                    self.xml_filepath = os.path.join(dirpath,fileM)
               elif 'boot' in fileM.lower():
                    self.boot_name=fileM
                    self.boot_filepath = os.path.join(dirpath,fileM)
               else:
                    pass

          zFile.close()
          return self.app_filepath,self.flash_filepath,self.xml_filepath,self.boot_filepath

     def parse_file(self,file_path):
          self.file_type = os.path.splitext(file_path)[-1]
          self.binfile_handle = bincopy.BinFile()
          if(self.file_type == '.hex' or self.file_type == '.HEX'):
               with open(file_path, 'r') as fin:
                    self.binfile_handle.add_ihex(fin.read())
               self.size = self.binfile_handle.segments.maximum_address - self.binfile_handle.segments.minimum_address
          if(self.file_type == '.bin' or self.file_type == '.BIN'):
               with open(file_path, 'rb') as fin:
                    self.binfile_handle.add_binary(fin.read())
          if(self.file_type == '.s19'):
               with open(file_path, 'r') as fin:
                    self.binfile_handle.add_srec(fin.read())
          # logging.info(binfile_handle.segments())  #All data

          
          return self.binfile_handle.segments
     